package cn.qyd.javareflect;

import com.sun.org.apache.bcel.internal.Const;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 邱运铎
 * @date 2024-03-04 0:08
 */
public class ReflectPersonDemo {
    public static void main(String[] args) throws NoSuchFieldException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException, ClassNotFoundException {

        //获取Person类的Class对象
        Class<?> clazz = Class.forName("cn.qyd.javareflect.Person");

        //获取并打印类名
        System.out.println(clazz.getName());

        //使用构造函数创建Person对象实例
        Constructor<?> constructor = clazz.getConstructor(String.class,int.class);
        Object object = constructor.newInstance("邱运铎",24);

        //获取并调用getName方法
        Method getNameMethode = clazz.getMethod("getName");
        String name = (String) getNameMethode.invoke(object);

        //获取并调用setName方法
        Method setAgeMethod = clazz.getMethod("setAge",int.class);
        setAgeMethod.invoke(object,25);

        //获取age私有成员变量，并访问值
        Field ageField = clazz.getDeclaredField("age");
        ageField.setAccessible(true);
        int age = ageField.getInt(object);
        System.out.println(name + " 的当前年龄为：" + age);

        //获取私有方法并调用
        Method privateMethod = clazz.getDeclaredMethod("privateMethod");
        privateMethod.setAccessible(true);
        privateMethod.invoke(object);


    }
}
